# -*- coding: utf-8 -*-
import math
from cProfile import label
from operator import index

import dearpygui.dearpygui as dpg
from dearpygui.dearpygui import add_group, does_item_exist
from utils.chart_to_deepseek import ChatCompletion

from utils.config_utils import ConfigManager
from utils.file_utils import FileManager
from utils.analysis_utils import AnalysisManager
from models.student import Database
import random
import threading
from ctypes import windll
import os

class MainWindow:
    def __init__(self):
        self.config = ConfigManager()
        self.db = Database(self.config.get("database.student_dbpath"))
        self.file_manager = FileManager(self.db)
        self.chart_with_ai = ChatCompletion(self.config)
        self.analysis_manager = AnalysisManager(self.db)
        self.subjects = ["语文", "数学", "外语", "物理", "化学", "生物"]  # 默认科目列表
        self.table_data = []
        self.table_dic = {}
        # 图像各点的x坐标
        self.curve_data_x = []
        # 图像各点的y坐标
        self.curve_data_y = {}
        # 图像各点的y坐标最大值
        self.curve_data_ymax = []
        # 当前图像的形式,True为曲线图，False为柱状图
        self.curve_type = True
        self.curve_weight = self.config.get("curve.curve_weight")
        self.series_weight = self.config.get("curve.series_weight")
        # 科目名称与数据库列名的映射
        self.subject_to_column = self.config.get("convert_dic.subject_to_column")
        self.ensub_to_chinesesub = self.config.get("convert_dic.ensub_to_chinesesub")

        self.FindWindow = windll.user32.FindWindowW
        self.SetWindowText = windll.user32.SetWindowTextW
        self.random_title = str(random.random())
        self.window_title = self.config.get("program_configuration.window_title")
        self.create_context()
        self.font_setting()
        self.create_window()
        self.create_menu_bar()
        self.running()

    def import_grades(self, sender, app_data):
        file_path = app_data['file_path_name']
        if not file_path:
            dpg.set_value("status", "未选择文件！")
            return
        # 提取文件名（不带扩展名）作为 exam_id
        exam_id = os.path.splitext(os.path.basename(file_path))[0]
        # 检查是否已导入
        if self.db.is_exam_imported(exam_id):
            dpg.set_value("status", f"文件已导入过！考试标识符: {exam_id}")
            return
        try:
            self.file_manager.import_from_excel(file_path, exam_id)
            dpg.set_value("status", f"成绩导入成功！考试标识符: {exam_id}, 文件路径: {file_path}")
            # 更新 exam_id_combo
            self.update_exam_id_combo()
        except Exception as e:
            dpg.set_value("status", f"导入失败: {str(e)}")

    def update_exam_id_combo(self):
        exam_ids = self.db.get_all_exam_ids()
        dpg.configure_item("exam_id_combo", items=exam_ids)

    def query_class_statistics(self):
        self.reset_curve()
        exam_id = dpg.get_value("exam_id_combo")
        if not exam_id:
            dpg.set_value("status", "请选择考试标识符！")
            return
        try:
            # print(f"查询考试 {exam_id} 的班级统计信息...")
            # 查询班级成绩统计信息
            statistics = self.db.get_class_statistics(exam_id)
            # print(f"查询结果: {statistics}")  # 打印查询结果
            if not statistics:
                dpg.set_value("status", f"没有找到考试 {exam_id} 的数据！")
                return
            # 获取对应的分数线
            score_threshold = self.db.get_score_threshold(exam_id)
            if score_threshold is None:
                dpg.set_value("status", f"请先为考试 {exam_id} 设置分数线！")
                return
            # 构建表格数据
            table_data = [["班级", "平均分", "最高分", "最低分", f"高于{score_threshold}分人数"]]
            for row in statistics:
                table_data.append([
                    row[0],  # 班级
                    f"{row[1]:.2f}",  # 平均分
                    f"{row[2]:.2f}",  # 最高分
                    f"{row[3]:.2f}",  # 最低分
                    str(row[4])  # 高于分数线人数
                ])
            # print(f"表格数据: {table_data}")  # 打印表格数据
            # 显示表格
            self.show_table(table_data)
            dpg.set_value("status", f"查询成功！考试标识符: {exam_id}, 分数线: {score_threshold}")
        except Exception as e:
            print(f"查询失败: {str(e)}")  # 打印异常信息
            dpg.set_value("status", f"查询失败: {str(e)}")

    def show_table(self, table_data):
        # 清空之前的表格内容
        if dpg.does_item_exist("statistics_table"):
            dpg.delete_item("statistics_table")
        # 创建表格
        with dpg.table(tag="statistics_table", parent="mainWindow",
                       row_background=True,
                       header_row=True):
            for col in table_data[0]:
                dpg.add_table_column(label=col)
            for row in table_data[1:]:
                with dpg.table_row():
                    for cell in row:
                        dpg.add_text(cell)
            self.curve_plotting(table_data)

    def analyze_by_class_callback(self):
        class_name = dpg.get_value("class_name_input")
        result = self.analysis_manager.analyze_by_class(class_name)
        dpg.set_value("analysis_result", result)

    def analyze_by_student_callback(self):
        name = dpg.get_value("student_name_input")
        result = self.analysis_manager.analyze_by_student(name)
        dpg.set_value("analysis_result", result)

    def set_window_title(self,old_title, new_title):
        """循环检测窗口是否生成，生成之后修改窗口标题"""
        while True:
            hwnd = self.FindWindow(None, old_title)
            if hwnd != 0:
                self.SetWindowText(hwnd, new_title)
                break

    def clear_database(self):
        try:
            self.db.reset_database()
            dpg.set_value("status", "数据库已清空并重置！")
        except Exception as e:
            dpg.set_value("status", f"清空数据库失败: {str(e)}")

    def close(self):
        dpg.destroy_context()

    def __del__(self):
        self.close()

    def create_context(self):
        dpg.create_context()
        dpg.create_viewport(title=self.random_title,
                            width=int(self.config.get("program_configuration.window_width")),
                            height=int(self.config.get("program_configuration.window_height")),
                            small_icon=self.config.get("pic_path.logo"),
                            large_icon=self.config.get("pic_path.logo"))

    def font_setting(self):

    # 加载中文字体
        font_path = self.config.get("fonts_path.msyahei")
        try:
            with dpg.font_registry():
                with dpg.font(font_path, 18) as default_font:  # 增加中文编码范围，防止问号
                    dpg.add_font_range_hint(dpg.mvFontRangeHint_Default)
                    dpg.add_font_range_hint(dpg.mvFontRangeHint_Chinese_Simplified_Common)
                    dpg.add_font_range_hint(dpg.mvFontRangeHint_Chinese_Full)
            dpg.bind_font(default_font)
        except Exception as e:
            print(f"字体加载失败: {e}")

    def create_window(self):
        with dpg.file_dialog(directory_selector=False, show=False,
                            user_data='test',
                             callback = self.import_grades,
                             tag = "file_dialog",
                             width=700,
                             height=400,
                             file_count=1,):
            # dpg.add_file_extension(".*")
            # dpg.add_file_extension("", color=(150, 255, 150, 255))
            dpg.add_file_extension(".xlsx", color=(255, 255, 0, 255)) # 只允许选择.xlsx文件
        with dpg.window(label="主窗口",tag="mainWindow", width=800, height=600):
            # 主界面内容
            with dpg.group(horizontal=True, tag="query_condition"):  # 将考试标识符和科目选择器水平排列
                dpg.add_text("选择考试标识符:")
                dpg.add_combo(tag="exam_id_combo", width=100)
                dpg.add_spacer(width=20)  # 添加间距
                dpg.add_text("选择科目:")
                dpg.add_combo(tag="subject_combo", items=self.subjects, width=100)
                dpg.add_spacer(width=20)  # 添加间距
                dpg.add_text("选择班级:")
                dpg.add_combo(tag="class_combo", width=100)
                dpg.add_spacer(width=20)  # 添加间距
                dpg.add_text("输入学生姓名:")
                dpg.add_input_text(tag="student_id", width=100)
                dpg.add_spacer(width=20)  # 添加间距
                dpg.add_button(label="查询", width=50 ,callback=lambda: self.query())
                dpg.add_spacer(width=20)  # 添加间距
                dpg.add_button(label="重置", width=50, callback=lambda: self.reset())
                # if not dpg.get_value("exam_id_combo")==None:
                #     dpg.add_spacer(width=20)  # 添加间距
                #     dpg.add_button(label="查询班级统计", callback=lambda: self.query_class_statistics())
                #     if not dpg.get_value("subject_combo")==None:
                #         dpg.add_spacer(width=20)  # 添加间距
                #         dpg.add_button(label="查询科目统计", callback=lambda: self.query_subject_statistics())


            # dpg.add_spacer(height=20)  # 添加垂直间距

            # # 查询按钮
            # with dpg.group(horizontal=True):  # 将查询按钮水平排列
            #     dpg.add_button(label="查询班级统计", callback=lambda: self.query_class_statistics())
            #     dpg.add_spacer(width=20)  # 添加间距
            #     dpg.add_button(label="查询科目统计", callback=lambda: self.query_subject_statistics())
            dpg.add_spacer(height=10)  # 添加垂直间距

            with dpg.group(horizontal=True,tag="curve_plotting"):
                pass
            dpg.add_spacer(height=5)  # 添加垂直间距
            with dpg.group(tag = "curve",horizontal=True):
                pass

            dpg.add_spacer(height=20)  # 添加垂直间距

            # 初始化 exam_id 下拉列表
            self.update_exam_id_combo()
            # 初始化科目下拉列表
            self.update_subject_combo()
            # 初始化班级下拉列表
            self.update_class_combo()

            # 主界面内容
            with dpg.group(horizontal=False):  # 主内容区域
                dpg.add_spacer()

            # 添加状态栏
            with dpg.group(horizontal=True, parent=dpg.add_group()):  # 状态栏区域
                dpg.add_text("状态:", tag="status_label")
                dpg.add_input_text(
                    tag="status",
                    default_value="程序运行中.......",
                    readonly=True,  # 设置为只读
                    width=1000,
                    height=25,
                    multiline=True  # 允许多行文本
                )
                # dpg.add_text("", tag="status", wrap=800)  # 状态信息显示区域
            # 将状态栏固定在窗口底部
            dpg.add_spacer()  # 添加一个占位符，将状态栏推到窗口底部

    def create_menu_bar(self):
        with dpg.menu_bar(parent="mainWindow"):
            # 文件菜单
            with dpg.menu(label="文件"):
                dpg.add_menu_item(label="导入", callback=lambda: dpg.show_item("file_dialog"))
                dpg.add_spacer(height=10)  # 添加垂直间距
                dpg.add_menu_item(label="退出", callback=lambda: dpg.stop_dearpygui())
            # 数据菜单
            with dpg.menu(label="数据"):
                dpg.add_menu_item(label="清空数据库", callback=lambda: self.clear_database())
            # 与DeepSeek对话
            with dpg.menu(label="与DeepSeek对话"):
                dpg.add_menu_item(label="与DeepSeek对话", callback=lambda: self.chat_with_deepseek())
            # 设置菜单
            with dpg.menu(label="设置"):
                dpg.add_menu_item(label="设置图像宽度", callback=lambda: self.set_bar_width())
                dpg.add_spacer(height=10)  # 添加垂直间距
                dpg.add_menu_item(label="批量设置考试的分数线", callback=lambda: self.set_score_thresholds())
                dpg.add_spacer(height=10)  # 添加垂直间距
                dpg.add_menu_item(label="大模型设置", callback=lambda: self.set_model())

    def running(self):
        dpg.setup_dearpygui()
        dpg.set_primary_window('mainWindow', True)
        dpg.show_viewport()
        threading.Thread(target=self.set_window_title, args=(self.random_title, self.window_title)).start()
        dpg.start_dearpygui()

    def set_score_thresholds(self):
        # 获取所有 exam_id
        exam_ids = self.db.get_all_exam_ids()
        if not exam_ids:
            dpg.set_value("status", "没有可用的考试数据！")
            return
        # 打开设置分数线的窗口
        with dpg.window(label="设置多个考试的分数线", width=400, height=300, tag="score_thresholds_window"):
            dpg.add_text("为每个考试设置分数线:")
            self.threshold_inputs = {}  # 存储每个 exam_id 的输入框
            for exam_id in exam_ids:
                default_threshold = self.db.get_score_threshold(exam_id) or 500
                with dpg.group(horizontal=True):
                    dpg.add_text(f"{exam_id}:")
                    self.threshold_inputs[exam_id] = dpg.add_input_int(default_value=default_threshold)
            dpg.add_button(label="保存", callback=lambda: self.save_score_thresholds())

    def save_score_thresholds(self):
        # 获取每个 exam_id 的分数线
        exam_thresholds = {
            exam_id: dpg.get_value(input_tag)
            for exam_id, input_tag in self.threshold_inputs.items()
        }
        # 批量设置分数线
        self.db.set_score_thresholds(exam_thresholds)
        dpg.set_value("status", "所有考试的分数线已设置！")
        # 关闭设置窗口
        dpg.delete_item("score_thresholds_window")

    def query_subject_statistics(self):
        """
            查询科目班级统计信息并显示在表格中。
        """
        self.reset_curve()
        exam_id = dpg.get_value("exam_id_combo")
        subject = dpg.get_value("subject_combo")
        if not exam_id or not subject:
            dpg.set_value("status", "请选择考试标识符和科目！")
            return
        try:
            # 获取对应的数据库列名
            subject_column = self.subject_to_column.get(subject)
            # print(subject_column)
            if not subject_column:
                dpg.set_value("status", f"科目 {subject} 未找到对应的列名！")
                return
            # 查询班级成绩统计信息
            statistics = self.db.get_subject_statistics(exam_id, subject_column)
            if not statistics:  # 检查结果是否为空
                dpg.set_value("status", f"没有找到考试 {exam_id} 的科目 {subject} 的班级统计信息！")
                return
            # 查询分数段分布
            score_distribution = self.db.get_subject_score_distribution(exam_id, subject_column)
            if not score_distribution:  # 检查结果是否为空
                dpg.set_value("status", f"没有找到考试 {exam_id} 的科目 {subject} 的分数段分布数据！")
                return
            # 构建表格数据
            table_data = [["班级", "平均分", "最高分", "最低分", "及格人数"]]
            # 添加分数段列标题
            score_ranges = [f"{s[0]}-{s[0] + 10} 分" for s in score_distribution]
            table_data[0].extend(score_ranges)
            # 添加班级统计信息和分数段分布
            for row in statistics:
                class_name = row[0]  # 获取班级名称
                # 获取当前班级的分数段分布
                class_distribution = self.db.get_class_score_distribution(exam_id, subject_column, class_name)
                distribution_counts = {s[0]: s[1] for s in class_distribution}
                # 构建表格行
                table_row = [
                    class_name,  # 班级
                    f"{row[1]:.2f}",  # 平均分
                    f"{row[2]:.2f}",  # 最高分
                    f"{row[3]:.2f}",  # 最低分
                    f"{row[4]}"  # 及格人数
                ]
                # 添加分数段分布
                for score_range in score_ranges:
                    start_score = int(float(score_range.split("-")[0]))
                    count = distribution_counts.get(start_score, 0)
                    table_row.append(str(count))
                table_data.append(table_row)
            # 显示表格
            self.show_table(table_data)
            dpg.set_value("status", f"查询成功！考试标识符: {exam_id}, 科目: {subject}")
        except Exception as e:
            dpg.set_value("status", f"查询失败: {str(e)}")

    def show_score_distribution(self, score_distribution):
        # 清空之前的分布内容
        if dpg.does_item_exist("score_distribution"):
            dpg.delete_item("score_distribution")
        # 显示分数段分布
        with dpg.group(tag="score_distribution", parent="main_window"):
            dpg.add_text("分数段分布:")
            for row in score_distribution:
                dpg.add_text(f"{row[0]}-{row[0] + 10} 分: {row[1]} 人")

    def query(self):
        """
            根据用户输入的条件查询数据并显示在表格中。
            """
        # 获取用户输入的条件
        # if not dpg.get_value("exam_id_combo") == None:
        #     dpg.add_spacer(width=20)  # 添加间距
        #     dpg.add_button(label="查询班级统计", callback=lambda: self.query_class_statistics())
        #     if not dpg.get_value("subject_combo") == None:
        #         dpg.add_spacer(width=20)  # 添加间距
        #         dpg.add_button(label="查询科目统计", callback=lambda: self.query_subject_statistics())
        self.reset_curve()
        exam_id = dpg.get_value("exam_id_combo")
        subject_id = dpg.get_value("subject_combo")
        if not dpg.get_value("subject_combo"):
            subject = None
        else:
            subject = self.subject_to_column[dpg.get_value("subject_combo")]
        class_name = dpg.get_value("class_combo")
        student_name = dpg.get_value("student_id")
        # print(exam_id, subject, class_name, student_name)

        if exam_id:
            if not does_item_exist("spacer_1"):
                dpg.add_spacer(width=20,parent="query_condition",tag="spacer_1")  # 添加间距
            if not does_item_exist("query_class_statistics_button"):
                dpg.add_button(label="查询班级统计", tag="query_class_statistics_button",callback=lambda: self.query_class_statistics(),parent="query_condition")
            if subject_id:
                if not does_item_exist("spacer_2"):
                    dpg.add_spacer(width=20,parent="query_condition",tag="spacer_2")  # 添加间距
                if not does_item_exist("query_subject_statistics_button"):
                    dpg.add_button(label="查询科目统计", tag="query_subject_statistics_button",callback=lambda: self.query_subject_statistics(),parent="query_condition")


        # 查询数据
        try:
            # 查询数据
            data = self.db.get_students_by_conditions(exam_id, subject, class_name, student_name)
            if not data:
                dpg.set_value("status", "没有找到符合条件的学生！")
                return

            # 获取表头
            if subject:
                # 如果指定了科目，表头为固定的几列
                subject_chi = self.ensub_to_chinesesub[subject]
                headers = ["考试", "姓名", "班级", f"{subject_chi}(分数)", f"{subject_chi}(校序)", f"{subject_chi}(班序)"]
            else:
                # 如果未指定科目，获取所有列名作为表头
                self.db.cursor.execute("PRAGMA table_info(students)")
                columns = self.db.cursor.fetchall()
                initial_headers = [col[1] for col in columns]  # 提取列名
                headers = []
                for header in initial_headers:
                    if header in self.ensub_to_chinesesub:
                        headers.append(self.ensub_to_chinesesub[header])


            # 构建表格数据
            table_data = [headers]  # 第一行为表头
            for row in data:
                table_data.append([str(item) for item in row])  # 将每一行数据转换为字符串

            # 显示表格
            self.show_table(table_data)
            dpg.set_value("status", "查询成功！")
        except Exception as e:
            dpg.set_value("status", f"查询失败: {str(e)}")

        # self.generate_pesent_analysis_button()

    def generate_present_analysis_button(self):
        student_name = dpg.get_value("student_id")
        exam_id = dpg.get_value("exam_id_combo")
        if student_name and exam_id:
            if not does_item_exist("spacer_5"):
                dpg.add_spacer(width=20, tag="spacer_5", parent="curve_plotting")
            if not does_item_exist("present_analysis"):
                dpg.add_button(label="生成评语", tag="present_analysis", callback=self.present_analysis,
                               parent="curve_plotting")
            # self.generate_ai_output_area()

    def generate_ai_output_area(self):
        if not does_item_exist("spacer_3"):
            dpg.add_spacer(width=20, tag="spacer_3", parent="curve")
        if not does_item_exist("ai_output"):
            dpg.add_input_text(
                parent="curve",
                tag="ai_output",
                default_value="等待回答.......",
                readonly=True,  # 设置为只读
                width=800,
                height=380,
                multiline=True  # 允许多行文本
            )

    def update_subject_combo(self):
        """
            从数据库中获取所有科目并更新 subject_combo 控件。
            """
        subjects = self.db.get_all_subjects()
        if not subjects:
            newsub = []
            for item in subjects:
                if not self.ensub_to_chinesesub[item]:
                    newsub.append(item)
            dpg.configure_item("subject_combo", items=newsub)

    def update_class_combo(self):
        """
           从数据库中获取所有班级并更新 class_combo 控件。
           """
        classes = self.db.get_all_classes()
        dpg.configure_item("class_combo", items=classes)

    def reset(self):
        """重置查询条件"""
        dpg.delete_item("spacer_1")
        dpg.delete_item("query_class_statistics_button")
        dpg.delete_item("spacer_2")
        dpg.delete_item("query_subject_statistics_button")
        dpg.set_value("exam_id_combo", "")
        dpg.set_value("subject_combo", "")
        dpg.set_value("class_combo", "")
        dpg.set_value("student_id", "")
        dpg.delete_item("table", children_only=True)
        dpg.delete_item("curve", children_only=True)
        dpg.delete_item("curve_plotting", children_only=True)
        dpg.delete_item("statistics_table")

    def curve_plotting(self,table_data):
        self.table_data = table_data
        self.table_dic = self.table_to_dict(table_data)
        dpg.delete_item("curve_plotting", children_only=True)
        header = table_data[0]
        dpg.add_text("曲线绘制: ",parent="curve_plotting")
        # dpg.add_spacer(height=20,parent="curve_plotting")
        dpg.add_spacer(width=20,parent="curve_plotting")
        dpg.add_combo(header,
                      label = "设置X轴数据",
                      parent="curve_plotting",
                      tag="set_x_axis_combo",
                      width=100)
        dpg.add_spacer(width=20, parent="curve_plotting")
        dpg.add_combo(header,
                      label="设置Y轴数据",
                      parent="curve_plotting",
                      tag="set_y_axis_combo",
                      width=100)
        dpg.add_spacer(width=20, parent="curve_plotting")
        dpg.add_button(label="绘制柱状图", width=80 ,callback=self.plot_curve,parent="curve_plotting")
        dpg.add_spacer(width=20, parent="curve_plotting")
        dpg.add_button(label="绘制曲线图", width=80, callback=self.plot_curve, parent="curve_plotting")
        dpg.add_spacer(width=20, parent="curve_plotting")
        dpg.add_button(label="清除图像", width=80, callback=self.reset_curve, parent="curve_plotting")
        self.generate_present_analysis_button()
        # dpg.add_spacer(width=20, tag="spacer_4" ,parent="curve_plotting")
        # dpg.add_button(label="AI分析", width=80, callback=self.ai_analysis, parent="curve_plotting")
        # print(type(table_data))
    def plot_curve(self,sender, app_data):
        # print(sender,app_data)
        # print(type(sender),type(app_data))
        label = dpg.get_item_label(sender)
        if label == "绘制柱状图":
            self.curve_type = False
        if label == "绘制曲线图":
            self.curve_type = True
        # print(label)
        if not dpg.get_item_children("curve")[1]:
            x_item = dpg.get_value("set_x_axis_combo")
            y_item = dpg.get_value("set_y_axis_combo")
            if not x_item or not y_item:
                dpg.set_value("status", "请选择X轴和Y轴数据！")
            else:
                dpg.add_spacer(width=30,parent="curve")
                with dpg.plot(label=f"{x_item}的{y_item}柱状图",tag="curve_plot",parent = "curve",width=700,height= 380):
                    dpg.add_plot_legend()
                    # 添加X轴和Y轴
                    dpg.add_plot_axis(dpg.mvXAxis, label=x_item, no_gridlines=True, tag="xaxis_tag")
                    dpg.set_axis_limits("xaxis_tag", 0, 100)
                    # dpg.fit_axis_data("xaxis_tag")
                    dpg.add_plot_axis(dpg.mvYAxis, label=y_item, tag="yaxis_tag")
                    # dpg.set_axis_limits("yaxis_tag", 0, 100)
                    # dpg.fit_axis_data("yaxis_tag")
                    self.set_curve_data(label)
                dpg.add_spacer(parent="curve")
        else:
            self.set_curve_data(label)
    def set_curve_data(self,label):
        x_item = dpg.get_value("set_x_axis_combo")
        y_item = dpg.get_value("set_y_axis_combo")
        x_data = self.table_dic[x_item]
        y_data = self.table_dic[y_item]
        y_data = [float(y) for y in y_data]
        ymax = int(float(max(y_data)))
        # print(ymax)
        ymax = math.ceil(ymax + 0.1 * ymax)
        # print(ymax)
        tick = int(100/(len(x_data) + 1))
        x = []
        ls_pairs = []
        for (index,item) in enumerate(x_data):
            ls = []
            ls.append(item)
            ls.append(tick*(index + 1))
            x.append(tick*(index + 1))
            ls_pairs.append(tuple(ls))

        if y_item in self.curve_data_y:
            dpg.set_value("status", f"{y_item}已经绘制！")
        else:
            self.curve_data_y[y_item] = y_data
            self.curve_data_ymax.append(ymax)
            self.curve_data_x = x
            # print(self.curve_data_x,self.curve_data_y,self.curve_data_ymax)

        # print(ymax,type(ymax))
        # dpg.set_item_label("curve_plot", f"{x_item}的{y_item}柱状图")
        dpg.set_item_label("xaxis_tag", x_item)
        # dpg.set_item_label("yaxis_tag", y_item)
        dpg.set_axis_ticks("xaxis_tag", tuple(ls_pairs))
        dpg.set_axis_limits("yaxis_tag", 0, max(self.curve_data_ymax))
        dpg.delete_item("yaxis_tag", children_only=True)
        index = 0
        first_curve_x_pos = [(x - ((self.curve_weight / 2) * len(self.curve_data_ymax)) ) for x in self.curve_data_x]
        for key,value in self.curve_data_y.items():
            # curve_type为当前图像的形式,True为曲线图，False为柱状图
            if not self.curve_type:
                # print("绘制柱状图")
                dpg.add_bar_series([((x +  self.curve_weight * index)+self.curve_weight/2) for x in first_curve_x_pos],value,parent="yaxis_tag",label = key,weight=self.curve_weight)
                index += 1
            if self.curve_type:
                # print("绘制曲线图")
                dpg.add_line_series(self.curve_data_x, value, parent="yaxis_tag", label= key)
        self.generate_ai_analysis_button()
        # if dpg.get_value("exam_id_combo") and dpg.get_value("student_id"):
        #     if not does_item_exist("spacer_5"):
        #         dpg.add_spacer(width=20, tag="spacer_5", parent="curve_plotting")
        #     if not does_item_exist("present_analysis"):
        #         dpg.add_button(label="生成评语", tag="present_analysis", callback=self.present_analysis,
        #                        parent="curve_plotting")
        #     if not does_item_exist("spacer_3"):
        #         dpg.add_spacer(width=20, tag="spacer_3", parent="curve")
        #
        #     if not does_item_exist("ai_output"):
        #         dpg.add_input_text(
        #             parent="curve",
        #             tag="ai_output",
        #             default_value="等待回答.......",
        #             readonly=True,  # 设置为只读
        #             width=800,
        #             height=380,
        #             multiline=True  # 允许多行文本
        #         )

                # exam_id = dpg.get_value("exam_id_combo")
                # subject_id = dpg.get_value("subject_combo")
                # # class_name = dpg.get_value("class_combo")
                # student_name = dpg.get_value("student_id")

    def generate_ai_analysis_button(self):
        if not does_item_exist("spacer_4"):
            dpg.add_spacer(width=20, tag="spacer_4", parent="curve_plotting")
        if not does_item_exist("ai_analysis_button"):
            dpg.add_button(label="AI分析", tag="ai_analysis_button", width=80, callback=self.ai_analysis,
                           parent="curve_plotting")

    def get_columns_data(self,header):
        """
        获取指定列的数据
        :param header: 某一列表头的数据
        :return: 该列后面的所有数据
        """
        # 获取表头行
        headers = self.table_data[0]
        # 找到目标列的索引
        try:
            column_index = headers.index(header)
        except ValueError:
            dpg.set_value("status",f"表头 '{header}' 未找到！")
            return []

        # 提取列数据（跳过表头行）
        column_data = [row[column_index] for row in self.table_data[1:]]
        return column_data

    def table_to_dict(self,table_data):
        """
        将表格数据转换为字典。
        Args:
            table_data (list): 表格数据，是一个二维列表，第一行为表头。
        Returns:
            dict: 字典，键为表头，值为该列的数据列表。
        """
        if not table_data:
            return {}

        # 获取表头
        headers = table_data[0]
        # 初始化字典
        result = {header: [] for header in headers}

        # 遍历每一行（跳过表头）
        for row in table_data[1:]:
            for i, value in enumerate(row):
                result[headers[i]].append(value)

        return result

    def reset_curve(self):
        dpg.delete_item("yaxis_tag", children_only=True)
        # 重置
        self.curve_data_x = {}
        self.curve_data_y = {}
        self.curve_data_ymax = []

    def set_bar_width(self):
        # 打开设置图像宽度的窗口
        with dpg.window(label="设置图形宽度", width=400, height=200, tag="set_bar_width_window"):
            with dpg.group(horizontal=True):
                dpg.add_text("设置柱形图的宽度:")
                dpg.add_spacer(width=30)
                dpg.add_combo(["1","2","3","4","5","6"],default_value="3",width=50,callback=self.set_bar_width_callback, tag="bar_width_radio_button")
            # dpg.add_spacer(height=20)
            # dpg.add_text("设置曲线图的宽度:")
            # dpg.add_combo(["1", "2", "3", "4", "5", "6"], default_value="2", callback=self.set_series_width_callback, tag="series_width_radio_button")
            # dpg.add_spacer(height=20)
            # dpg.add_button(label="确定", callback=self.set_bar_width_window_callback, user_data="确定")

    # def set_bar_width_window_callback(self, sender, app_data):
    #     self.set_bar_width_callback(sender, app_data)
    #     self.set_series_width_callback(sender, app_data)
    #     dpg.delete_item("set_bar_width_window")

    def set_bar_width_callback(self, sender, app_data):
        new_bar_weight = int(dpg.get_value("bar_width_radio_button"))
        self.curve_weight = new_bar_weight
        self.config.set('curve.curve_weight', new_bar_weight)
        dpg.set_value("status", f"柱形宽度成功设置为{new_bar_weight}！")
        dpg.delete_item("set_bar_width_window")
    #
    # def set_series_width_callback(self, sender, app_data):
    #     new_series_weight = int(dpg.get_value("series_width_radio_button"))
    #     self.series_weight = new_series_weight
    #     self.config.set('curve.series_weight', new_series_weight)
    #     dpg.set_value("status", f"曲线的宽度成功设置为{new_series_weight}！")
    def set_model(self):
        with dpg.window(label="设置DeepSeek参数", width=1000, height=400, tag="set_bar_width_window"):
            dpg.add_text("本程序使用了硅基流动的API接口，请设置相关参数:")
            dpg.add_spacer(height=30)
            with dpg.group(horizontal=True):
                dpg.add_text("请选择使用的模型：")
                dpg.add_spacer(width=20)
                dpg.add_combo(["DeepSeek-V3", "DeepSeek-R1"],
                              tag="mode_selection",
                              default_value="DeepSeek-V3", width=150,
                              callback=self.set_model_type)
                # dpg.add_spacer(width=20)
                # dpg.add_button(label="设置", callback=self.set_model_type)
            dpg.add_spacer(height=30)
            with dpg.group(horizontal=True):
                dpg.add_text("请设置API Token:")
                dpg.add_spacer(width=20)
                dpg.add_input_text(default_value="请输入硅基流动的API Token",
                                   width=500,
                                   tag="api_token_input",
                                   callback=self.set_api_token)
                # dpg.add_spacer(width=20)
            dpg.add_spacer(height=30)
            with dpg.group(horizontal=True):
                dpg.add_spacer(width=700)
                dpg.add_button(label="保存并关闭", callback=self.set_ai_api)

                # api_token: sk - gnzfezheslpjhzcqywkedilpbybnlufhhwexvxoxzjzmgqbp
                # model: deepseek-ai/DeepSeek-V3
                # deepseek-ai/DeepSeek-R1

    def set_model_type(self, sender,app_data):
        # print(app_data,sender)
        data = "deepseek-ai/" + app_data
        # print(data)
        self.config.set('api_setting.model', data)
        dpg.set_value("status", f"模型成功设置为{app_data}！")

    def set_api_token(self,sender,app_data):
        # print(app_data,sender)
        self.config.set('api_setting.api_token', app_data)
        dpg.set_value("status", f"API Token成功设置为{app_data}！")

    def set_ai_api(self):
        dpg.set_value("status", f"模型成功设置为{dpg.get_value("mode_selection")}！API Token成功设置为{dpg.get_value('api_token_input')}！")
        dpg.delete_item("set_bar_width_window")
    #     self.set_model_type()
    #     self.set_api_token()
    def chat_with_deepseek(self):
        with dpg.window(label="与DeepSeek对话", width=1200, height=800, tag="chat_with_deepseek_window"):
            with dpg.group(horizontal=True):
                dpg.add_text("请输入你想问的问题：")
                dpg.add_spacer(width=20)
                dpg.add_input_text(default_value="请输入你想问的问题", width=500, tag="chat_input")
                dpg.add_spacer(width=20)
                dpg.add_button(label="发送", callback=self.send_chat)
            dpg.add_spacer(height=30)
            with dpg.group(horizontal=True):
                dpg.add_text("DeepSeek的回答：")
                dpg.add_input_text(default_value="DeepSeek的回答：",
                                   multiline=True,
                                   width=1000,height=600, tag="chat_output", readonly=True)
                # dpg.add_spacer(width=700)
                # dpg.add_button(label="发送", callback=self.send_chat)

    def send_chat(self):
        question = dpg.get_value("chat_input")
        anser = ""
        for content in self.chart_with_ai.get_chat_completion(messages=question):
            anser += content
            dpg.set_value("chat_output", anser)

    def ai_analysis(self):
        self.generate_ai_output_area()
        exam_id = dpg.get_value("exam_id_combo")
        subject_id = dpg.get_value("subject_combo")
        # class_name = dpg.get_value("class_combo")
        student_name = dpg.get_value("student_id")
        x_item = dpg.get_value("set_x_axis_combo")
        y_item = dpg.get_value("set_y_axis_combo")
        x_data = self.table_dic[x_item]
        y_data = self.table_dic[y_item]
        # print(x_item,y_item)
        # print(x_data,y_data)
        question = ""
        if student_name:
            question += f"{student_name}同学,"
        if exam_id:
            question += f"{exam_id}考试中，"
        if subject_id:
            question += f"{subject_id}科目的成绩,"
        question += f"{x_item}是{x_data}，其{y_item}对应的是{y_data}，请分析一下其数据变化，并给出针对性的建议。"
        # print(question)
        anser = ""
        for content in self.chart_with_ai.get_chat_completion(messages=question):
            anser += content
            dpg.set_value("ai_output", anser)

    def present_analysis(self):
        # print(self.table_data)
        self.generate_ai_output_area()
        exam_id = dpg.get_value("exam_id_combo")
        # subject_id = dpg.get_value("subject_combo")
        # class_name = dpg.get_value("class_combo")
        student_name = dpg.get_value("student_id")
        question = f'这是{student_name}同学在{exam_id}考试中的成绩，'
        question += (f"本次考试汇总的项目有{self.table_data[0]}, 各项目对应的数据为{self.table_data[1]}，请分析一下{student_name}同学在本次考试中的，各个科目的成绩及排名，给出积极的评价与建议。")
        # print(question)
        anser = ""
        for content in self.chart_with_ai.get_chat_completion(messages=question):
            anser += content
            dpg.set_value("ai_output", anser)



